package copy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 聊天室服务端
 * @author soft01
 *
 */

public class Server {
	/**
	 * 运行在服务端的ServerSocket
	 * 主要有两个作用：
	 * 1：向系统申请服务端口，客户端就是通过这个端口与客户端建立连接的
	 * 2：监听端口，一旦一个客户端连接了则会实例化一个Socket 通过这个Socket
	 * 就可以与刚建立连接的客户端交互
	 */
	private ServerSocket serverSocket;
	private InputStream serverInputStream;
	private OutputStream serverOutputStream;
	private ArrayList<Clienter> clientList;
	/*
	 * 服务端初始化的方法
	 */
	public Server() {		
		try {
			/*
			 * 实例化ServerSocket的同时指定服务端口
			 * 如果该端口被系统的其他程序占用，则会抛出异常
			 */
			clientList=new ArrayList<>();
			System.out.println("服务端正在启动......");
			serverSocket=new ServerSocket(8088);
			System.out.println("服务端启动成功");		
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	/*
	 * 服务端启动方法
	 */
	public static void main(String[] args) {
		Server server=new Server();
		server.serverStart();
	}
	public void serverStart() {
		while(true) {			
			try {
				System.out.println("等待一个客户端连接");
				Socket socket = serverSocket.accept();
				System.out.println("客户端连接了");
				serverInputStream = socket.getInputStream();	
				
				serverOutputStream=socket.getOutputStream();
				
				String ip=socket.getInetAddress().getHostAddress();
				
				BufferedReader br=PrintWBufferedR.getBR(serverInputStream);
				
				PrintWriter pw =PrintWBufferedR.getPW(serverOutputStream);	
				
				ObjectInputStream ois=ObjectStream.getObjInStream(serverInputStream);
				
				ObjectOutputStream oos=ObjectStream.getObjOutStream(serverOutputStream);
				
				Clienter clienter = new Clienter(br,pw,ip,ois,oos);
				clientList.add(clienter);
				ClientHander ch = new ClientHander(clienter,clientList);
				Thread thread=new Thread(ch);
				thread.start();
			} catch (IOException e) {
				e.printStackTrace();
			}													
		}					
	}
	
}
